package com.zhiche.lisa.bms.service.price.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.zhiche.lisa.bms.dao.mapper.driver.FuelTypeMapper;
import com.zhiche.lisa.bms.dao.mapper.price.PricePurchaseDtlMapper;
import com.zhiche.lisa.bms.dao.mapper.price.PricePurchaseMapper;
import com.zhiche.lisa.bms.dao.model.driver.FuelPriceEffective;
import com.zhiche.lisa.bms.dao.model.driver.FuelType;
import com.zhiche.lisa.bms.dao.model.driver.PertrolPriceEffective;
import com.zhiche.lisa.bms.dao.model.driver.VehicleClassify;
import com.zhiche.lisa.bms.dao.model.fee.FeePayable;
import com.zhiche.lisa.bms.dao.model.prepay.PrepayBill;
import com.zhiche.lisa.bms.dao.model.price.*;
import com.zhiche.lisa.bms.enums.RateTransformEnum;
import com.zhiche.lisa.bms.pojo.dto.driver.HycOrderData;
import com.zhiche.lisa.bms.pojo.dto.price.PricePurchaseAndDtlDTO;
import com.zhiche.lisa.bms.pojo.dto.util.BmsServiceResult;
import com.zhiche.lisa.bms.pojo.dto.util.integration.ShipTaskDTO;
import com.zhiche.lisa.bms.pojo.dto.util.integration.ShipmentDTO;
import com.zhiche.lisa.bms.pojo.dto.util.mdm.TransportationTypeDTO;
import com.zhiche.lisa.bms.pojo.vo.fee.FeePayableVO;
import com.zhiche.lisa.bms.pojo.vo.price.PricePurchaseDetailVO;
import com.zhiche.lisa.bms.pojo.vo.price.PricePurchaseVO;
import com.zhiche.lisa.bms.service.bill.BillService;
import com.zhiche.lisa.bms.service.driver.IFuelPriceEffectiveService;
import com.zhiche.lisa.bms.service.driver.IVehicleClassifyService;
import com.zhiche.lisa.bms.service.driver.PertrolPriceEffectiveService;
import com.zhiche.lisa.bms.service.fee.FeePayableService;
import com.zhiche.lisa.bms.service.prepay.PrepayBillService;
import com.zhiche.lisa.bms.service.price.*;
import com.zhiche.lisa.bms.service.utils.HycApiUtil;
import com.zhiche.lisa.bms.service.utils.LspUtil;
import com.zhiche.lisa.bms.service.utils.MdmUtil;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.service.utils.common.AccountBindUtil;
import com.zhiche.lisa.bms.service.utils.common.BeanColumnUtil;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 支付价格 服务实现类
 * </p>
 *
 * @author liuanshun
 * @since 2018-08-29
 */
@Service
public class PricePurchaseServiceImpl extends ServiceImpl<PricePurchaseMapper, PricePurchase> implements PricePurchaseService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PricePurchaseServiceImpl.class);

    @Autowired
    private OtmUtil otmUtil;

    @Autowired
    private PriceDeductRateService priceDeductRateService;

    @Autowired
    private PriceIncomingService priceIncomingService;

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private BillService billService;

    @Autowired
    private PrepayBillService prepayBillService;

    @Autowired
    private PriceFiRateService priceFiRateService;

    @Autowired
    private PricePurchaseDtlService pricePurchaseDtlService;

    @Value("${lisa.socketTimeout}")
    private int socketTimeout;

    @Value("${lisa.tms.queryPurchasePriceOtmUrl}")
    private String queryPurchasePriceOtmUrl;

    @Value("${lisa.integration.url}")
    private String integrationUrl;

    @Value("${lisa.tms.url}")
    private String tmsUrl;

    @Autowired
    private FeePayableService feePayableService;

    @Autowired
    private LspUtil lspUtil;

    @Autowired
    private PertrolPriceEffectiveService pertrolPriceEffectiveService;

    @Autowired
    private IVehicleClassifyService vehicleClassifyService;

    @Autowired
    private PricePurchaseDtlMapper pricePurchaseDtlMapper;

    @Autowired
    private IFuelPriceEffectiveService fuelPriceEffectiveService;

    @Autowired
    private FuelTypeMapper fuelTypeMapper;

    @Autowired
    private HycApiUtil hycApiUtil;

    /**
     * 支付价格分页列表
     *
     * @param page
     * @return
     */
    @Override
    public Page<PricePurchase> queryPurchasePage(Page<PricePurchase> page) {
        EntityWrapper<PricePurchase> ew = this.getPurchaseCondition(page.getCondition());
        ew.orderBy("gmt_create desc, id desc");
        //清空page附加条件值
        page.setCondition(Maps.newHashMap());
        List<PricePurchase> pricePurchases = baseMapper.selectPage(page, ew);
        pricePurchases.forEach(pricePurchase -> {
            BigDecimal extPurchasePrice = this.getExtPurchasePrice(pricePurchase);
            pricePurchase.setExtPurchasePrice(extPurchasePrice);
            //默认执行价返回与暂估价相同
            if (Objects.isNull(pricePurchase.getActPurchasePrice())) {
                pricePurchase.setActPurchasePrice(extPurchasePrice);
            }
        });
        page.setRecords(pricePurchases);
        return page;
    }

    /**
     * 支付价格列表
     *
     * @param condition
     * @return
     */
    @Override
    public List<PricePurchase> queryPurchaseList(Map<String, Object> condition) {
        EntityWrapper<PricePurchase> ew = this.getPurchaseCondition(condition);
        //清空page附加条件值
        List<PricePurchase> pricePurchases = baseMapper.selectList(ew);
        pricePurchases.forEach(pricePurchase -> {
            BigDecimal extPurchasePrice = this.getExtPurchasePrice(pricePurchase);
            pricePurchase.setExtPurchasePrice(extPurchasePrice);
            //默认执行价返回与暂估价相同
            if (Objects.isNull(pricePurchase.getActPurchasePrice())) {
                pricePurchase.setActPurchasePrice(extPurchasePrice);
            }
        });
        return pricePurchases;
    }

    /**
     * 获取标准价
     *
     * @param pricePurchase
     * @return
     */
    @Override
    public BigDecimal getExtPurchasePrice(PricePurchase pricePurchase) {
        BigDecimal deductRate = null;
        PriceDeductRate priceDeductRate = priceDeductRateService.returnPriceDeductRate(pricePurchase.getLspId(), pricePurchase.getFleetId());
        if (Objects.nonNull(priceDeductRate) && Objects.nonNull(priceDeductRate.getRate())) {
            deductRate = priceDeductRate.getRate().setScale(2, BigDecimal.ROUND_HALF_UP);
        } else {
            deductRate = new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        if (Objects.isNull(pricePurchase.getExtPurchasePrice())) {
            pricePurchase.setExtPurchasePrice(new BigDecimal(0));
        }
        return pricePurchase.getExtPurchasePrice().multiply(deductRate).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 查询条件
     *
     * @param condition
     * @return
     */
    private EntityWrapper<PricePurchase> getPurchaseCondition(Map<String, Object> condition) {
        EntityWrapper<PricePurchase> ew = new EntityWrapper<>();
        if (!CollectionUtils.isEmpty(condition)) {
            if (condition.containsKey("$tableFieMap")) {
                for (Map.Entry<String, String> entry :
                        ((Map<String, String>) condition.get("$tableFieMap")).entrySet()) {
                    ew.eq(entry.getValue(), condition.get(entry.getKey()));
                }
            } else {
                //遍历条件
                for (Map.Entry<String, Object> entry :
                        condition.entrySet()) {
                    if (!Strings.isNullOrEmpty(entry.getKey())) {
                        //如果传入的选中承运商不为空，增加承运商匹配条件
                        if ("lspId".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                            ew.eq("lsp_id", entry.getValue());
                        }
                        //如果传入的选中车队不为空，增加车队匹配条件
                        if ("fleetId".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                            ew.eq("fleet_id", entry.getValue());
                        }
                        //如果传入的选中车牌不为空，增加车牌匹配条件
//                    if ("carrierPlate".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue()))
//                        ew.eq("carrier_plate", entry.getValue());
                        if ("carrierPlate".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                            ew.eq("carrier_id", entry.getValue());
                        }
                        //增加生效筛选条件
                        if ("enable".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                            ew.eq("is_enable", "0".equals(entry.getValue()) ? false : true);
                        }
                        //任务号，指令号，车架号
//                    if ("code".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
//                        ew.andNew().like("shipment_code", String.valueOf(entry.getValue())).or().
//                                like("ship_task_code", String.valueOf(entry.getValue())).or().
//                                like("item_uid", String.valueOf(entry.getValue()));
//                    }
                        if ("mobile".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {
                            ew.andNew().like("lsp_name", String.valueOf(entry.getValue())).or().
                                    like("fleet_name", String.valueOf(entry.getValue())).or().
                                    like("carrier_plate", String.valueOf(entry.getValue()));
                        }
                    }
                }
            }
        }
        ew.andNew().eq("is_delete", 0).or().isNull("is_delete");
        return ew;
    }

    /**
     * 根据id号获取支付价格
     *
     * @param ids
     * @return
     */
    @Override
    public List<PricePurchase> getPricePurchaseListByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BaseException("请选择需要调价的指令");
        }
        //根据指定id数据获取结果集
        List<PricePurchase> pricePurchases = baseMapper.selectBatchIds(ids);
        return pricePurchases;
    }

    /**
     * 新增支付价格信息
     *
     * @param pricePurchase
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertPurchase(PricePurchase pricePurchase) {
        if (Objects.isNull(pricePurchase.getShipmentCode())) {
            throw new BaseException("请绑定装车单编号");
        }
        if (Objects.isNull(pricePurchase.getShipTaskCode())) {
            throw new BaseException("请绑定运输任务编号");
        }
        //验证并绑定登陆信息
        if (Objects.isNull(pricePurchase.getLspId())) {
            throw new BaseException("请绑定承运商");
        }
        new AccountBindUtil<PricePurchase>().bindCreatorAndTenantId(pricePurchase, true);
        //去除暂执行价和溢价比传入值
        pricePurchase.setActPurchasePrice(null);
        pricePurchase.setOverflowRate("0");
        pricePurchase.setEnable(true);
        BigDecimal deductRate = null;
        if (Objects.nonNull(pricePurchase.getExtPurchasePrice())) {
            PriceDeductRate priceDeductRate = priceDeductRateService.returnPriceDeductRate(pricePurchase.getLspId(), pricePurchase.getFleetId());
            if (Objects.nonNull(priceDeductRate) && Objects.nonNull(priceDeductRate.getPayWay())) {
                //标准价
                if ("1".equals(priceDeductRate.getPayWay())) {
                    if (Objects.nonNull(priceDeductRate.getRate())) {
                        BigDecimal price = pricePurchase.getExtPurchasePrice().multiply(priceDeductRate.getRate());
                        pricePurchase.setActPurchasePrice(price);
                    }
                } else if ("2".equals(priceDeductRate.getPayWay())) {
                    pricePurchase.setActPurchasePrice(pricePurchase.getExtPurchasePrice());
                }
                deductRate = priceDeductRate.getRate();
            }
        }
        baseMapper.insert(pricePurchase);
        //更新溢价比
//        this.updateOverflowRate(pricePurchase, deductRate, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void importPurchaseAndDtl(PricePurchaseAndDtlDTO pricePurchaseAndDtlDTO) {
        try {
            if (Strings.isNullOrEmpty(pricePurchaseAndDtlDTO.getLoadStatus())) {
                PricePurchase pricePurchase = new PricePurchase();
                BeanUtils.copyProperties(pricePurchaseAndDtlDTO, pricePurchase);
                PricePurchaseDtl pricePurchaseDtl = pricePurchaseAndDtlDTO.getPricePurchaseDtl();
                if (Strings.isNullOrEmpty(pricePurchase.getDepartAdressName())) {
                    pricePurchase.setDepartAdressName(
                            (pricePurchaseAndDtlDTO.getStartProvince() == null ? "" : pricePurchaseAndDtlDTO.getStartProvince()) +
                                    (pricePurchaseAndDtlDTO.getStartCity() == null ? "" : pricePurchaseAndDtlDTO.getStartCity()) +
                                    (pricePurchaseAndDtlDTO.getStartCounty() == null ? "" : pricePurchaseAndDtlDTO.getStartCounty())
                    );
                }
                if (Strings.isNullOrEmpty(pricePurchase.getDestAdderssName())) {
                    pricePurchase.setDestAdderssName(
                            (pricePurchaseAndDtlDTO.getEndProvince() == null ? "" : pricePurchaseAndDtlDTO.getEndProvince()) +
                                    (pricePurchaseAndDtlDTO.getEndCity() == null ? "" : pricePurchaseAndDtlDTO.getEndCity()) +
                                    (pricePurchaseAndDtlDTO.getEndCounty() == null ? "" : pricePurchaseAndDtlDTO.getEndCounty())
                    );
                }
                this.deleteDuplicationWaybillId(pricePurchase.getWaybillDtlId());
                this.insertPurchase(pricePurchase);
                //人送来源进行详明保存
                if ("20".equals(pricePurchase.getCreateFrom())) {
                    if (pricePurchaseDtl.getFirstOilCapacity() == null) {
                        pricePurchaseDtl.setFirstOilCapacity(BigDecimal.ZERO);
                    }
                    if (pricePurchaseDtl.getFirstOilTotal() == null) {
                        pricePurchaseDtl.setFirstOilTotal(BigDecimal.ZERO);
                    }
                    pricePurchase.setActPurchasePrice(pricePurchaseDtl.getSumCost() == null ? BigDecimal.ZERO : pricePurchaseDtl.getSumCost());
                    pricePurchase.setMileage(pricePurchaseDtl.getKilometer());
                    pricePurchase.setDealFlag(0);
                    this.updateById(pricePurchase);
                    pricePurchaseDtlService.insertPricePurchaseDtl(pricePurchaseDtl, pricePurchase.getId());

                    // // 生成账款和预付账单
                    // sendDriverToCreateFeePayableAndPrebill(pricePurchaseAndDtlDTO, pricePurchase, pricePurchaseDtl);
                    //
                    // // 价格数据乘以系数进行推送
                    // computePrice(pricePurchaseDtl, pricePurchase.getLspId());
                    //
                    // // 推送OTM人送价格
                    // putOtmSendPrice(pricePurchaseDtl, pricePurchase.getVehicleClassifyId());
                }
            } else {
                //获取对应支付价格数据
                PricePurchase pricePurchase = new PricePurchase();
                BeanUtils.copyProperties(pricePurchaseAndDtlDTO, pricePurchase);
                pricePurchase.setTenantId(null);
                pricePurchase.setCreator(null);
                EntityWrapper<PricePurchase> ew = new EntityWrapper<>();

                List<PricePurchase> pricePurchases = baseMapper.selectListNoTenant(getPurchaseCondition(BeanColumnUtil.objectToMap(pricePurchase)));
                pricePurchase = CollectionUtils.isEmpty(pricePurchases) ? null : pricePurchases.get(0);

                if (pricePurchase == null || pricePurchase.getId() == null) {
                    throw new BaseException("未匹配到对应支付价格");
                }
                List<PricePurchaseDtl> pricePurchaseDtls = pricePurchaseDtlService.selectPricePurchaseDtlByHeadId(pricePurchase.getId());
                if (CollectionUtils.isEmpty(pricePurchaseDtls)) {
                    throw new BaseException("未匹配到对应支付价格明细");
                }
                PricePurchaseDtl pricePurchaseDtl = pricePurchaseDtls.get(0);

                // 更新装车单状态
                updateFeepaybleAndPrebillLoasStatus(pricePurchase, pricePurchaseDtl, pricePurchaseAndDtlDTO.getLoadStatus(), pricePurchaseAndDtlDTO.getShipmentDate());
                // 生成账款和预付账单
                // sendDriverToCreateFeePayableAndPrebill(pricePurchaseAndDtlDTO, pricePurchase, pricePurchaseDtl);

                // 2019-01-10 产品说的要注释
                // //生成应付账单
                // Bill bill = new Bill();
                // bill.setIsAffirm(0);
                // bill.setBillStatus("10");
                // bill.setBillProp(0);
                // bill.setBillType("20");
                // bill.setNum(1);
                // bill.setPayerId(feePayable.getPayerId());
                // bill.setPayerName(feePayable.getPayerName());
                // bill.setPayeeId(feePayable.getPayeeId());
                // bill.setPayeeName(feePayable.getPayeeName());
                // new AccountBindUtil<Bill>().bindCreatorAndTenantId(bill, true);
                // billService.insertBillOne(bill);

                //价格数据乘以系数进行推送
                // computePrice(pricePurchaseDtl, pricePurchase.getLspId());

                // 推送OTM人送价格
                // putOtmSendPrice(pricePurchaseDtl);
            }
        } catch (BaseException e) {
            LOGGER.error("PricePurchaseServiceImpl.importPurchaseAndDtl error: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("PricePurchaseServiceImpl.importPurchaseAndDtl error: {}", e.getMessage());
            throw new BaseException("新增支付价格和详明错误");
        }

    }

    /**
     * 删除已经存在的数据
     *
     * @param orderReleaseId
     */
    private void deleteDuplicationWaybillId(String orderReleaseId) {
        // 根据 - or删除重复的数据
        if (!StringUtils.isEmpty(orderReleaseId)) {
            EntityWrapper<PricePurchase> ew = new EntityWrapper<>();
            ew.eq("waybill_dtl_id", orderReleaseId);
            this.delete(ew);

            // 删除账款
            EntityWrapper<FeePayable> feeEw = new EntityWrapper<>();
            feeEw.eq("waybill_dtl_id", orderReleaseId);
            feeEw.eq("status", 0);
            FeePayable updateFeepay = new FeePayable();
            updateFeepay.setStatus(2);
            feePayableService.update(updateFeepay, feeEw);

            // 删除预付
            EntityWrapper<PrepayBill> preBillEw = new EntityWrapper<>();
            preBillEw.eq("waybill_dtl_id", orderReleaseId);
            PrepayBill updatePrebill = new PrepayBill();
            updatePrebill.setStatus(40);
            prepayBillService.update(updatePrebill, preBillEw);
        }
    }

    /**
     * 更新账款和预付账单装车单状态为已发运
     *
     * @param pricePurchase
     * @param pricePurchaseDtl
     */
    private void updateFeepaybleAndPrebillLoasStatus(PricePurchase pricePurchase, PricePurchaseDtl pricePurchaseDtl,
                                                     String loadStatus, String shipmentDate) {
        FeePayable oldFeePayable = getOldFeePayable(pricePurchaseDtl.getOrderlineId(), pricePurchase);
        if (oldFeePayable != null) {
            oldFeePayable.setLoadStatus(loadStatus);
            // 2019-09-06 更新发运时间
            Date shipDate = null;
            if (!StringUtils.isEmpty(shipmentDate)) {
                if (shipmentDate.contains("/")) {
                    shipDate = ToolCommonUtils.getDateByStr(shipmentDate, ToolCommonUtils.FORMAT_PARTTEN_3);
                } else if (shipmentDate.contains("-")) {
                    shipDate = ToolCommonUtils.getDateByStr(shipmentDate, ToolCommonUtils.FORMAT_PARTTEN_2);
                }
            }
            oldFeePayable.setOrderDate(shipDate);
            feePayableService.updateById(oldFeePayable);

            PrepayBill oldPreBill = getOldPreBill(oldFeePayable.getId());
            if (oldPreBill != null) {
                // 2019-09-06 更新发运时间
                oldPreBill.setOrderDate(shipDate);
                oldPreBill.setLoadStatus(loadStatus);
                prepayBillService.updateById(oldPreBill);
            }
        }
    }

    /**
     * 推送OTM人送价格
     *
     * @param pricePurchaseDtl
     */
    private void putOtmSendPrice(PricePurchaseDtl pricePurchaseDtl, String vehicleTypeId) {
        // 获取油类型
        String oilType = null;
        if (!StringUtils.isEmpty(vehicleTypeId)) {
            List<FuelType> fuelTypeList = fuelTypeMapper.getFuelTypeByVehicleId(vehicleTypeId);
            if (!CollectionUtils.isEmpty(fuelTypeList)) {
                oilType = fuelTypeList.get(0).getFuelName();
            }
        }

        BmsServiceResult bmsServiceResult = otmUtil.getSavePriceByRs(pricePurchaseDtl, oilType);
        // if (bmsServiceResult == null) {
        //     throw new BaseException("数据同步OTM失败");
        // }
        // if (!bmsServiceResult.isSuccess()) {
        //     throw new BaseException(bmsServiceResult.getMessage());
        // }
    }

    /**
     * 计算价格
     *
     * @param pricePurchaseDtl
     * @param lspId
     */
    private void computePrice(PricePurchaseDtl pricePurchaseDtl, Long lspId) {
        // BigDecimal fiRate = RateTransformEnum.SEND_DRIVER_RATE.getRate();
        // 2019-06-06修改 不区分运输方式, 统一使用 1.062 比例系数
        BigDecimal fiRate = RateTransformEnum.OTHER_RATE.getRate();
        // 获取对应的财务系数
        // PriceFiRate priceFiRate = priceFiRateService.queryPriceFiRateById(lspId);
        // //使用获取的财务系数，如不存在默认1
        // if (Objects.nonNull(priceFiRate) && Objects.nonNull(priceFiRate.getFiRate())) {
        //     fiRate = priceFiRate.getFiRate().setScale(2, BigDecimal.ROUND_HALF_UP);
        // } else {
        //     fiRate = BigDecimal.ONE.setScale(2, BigDecimal.ROUND_HALF_UP);
        // }

        pricePurchaseDtl.setFirstOilTotal(
                fiRate.multiply(
                        pricePurchaseDtl.getFirstOilTotal() == null ? BigDecimal.ZERO : pricePurchaseDtl.getFirstOilTotal()
                ).setScale(2, BigDecimal.ROUND_HALF_UP));
        pricePurchaseDtl.setCardOilTotal(
                fiRate.multiply(
                        pricePurchaseDtl.getCardOilTotal() == null ? BigDecimal.ZERO : pricePurchaseDtl.getCardOilTotal()
                ).setScale(2, BigDecimal.ROUND_HALF_UP));
        pricePurchaseDtl.setOilCost(
                fiRate.multiply(
                        pricePurchaseDtl.getOilCost() == null ? BigDecimal.ZERO : pricePurchaseDtl.getOilCost()
                ).setScale(2, BigDecimal.ROUND_HALF_UP));
        pricePurchaseDtl.setOilPrice(
                fiRate.multiply(
                        pricePurchaseDtl.getOilPrice() == null ? BigDecimal.ZERO : pricePurchaseDtl.getOilPrice()
                ).setScale(2, BigDecimal.ROUND_HALF_UP));
        pricePurchaseDtl.setOilPrice(
                fiRate.multiply(
                        pricePurchaseDtl.getOilPrice() == null ? BigDecimal.ZERO : pricePurchaseDtl.getOilPrice()
                ).setScale(2, BigDecimal.ROUND_HALF_UP));
        pricePurchaseDtl.setServiceWage(
                fiRate.multiply(
                        pricePurchaseDtl.getServiceWage() == null ? BigDecimal.ZERO : pricePurchaseDtl.getServiceWage()
                ).setScale(2, BigDecimal.ROUND_HALF_UP));
    }


    /**
     * 新增或修改应付账款和预付订单
     *
     * @param pricePurchaseAndDtlDTO
     * @param pricePurchase
     * @param pricePurchaseDtl
     */
    private void sendDriverToCreateFeePayableAndPrebill(PricePurchaseAndDtlDTO pricePurchaseAndDtlDTO,
                                                        PricePurchase pricePurchase, PricePurchaseDtl pricePurchaseDtl) {
        // 判断是否存在, 存在则生成
        FeePayable oldFeePayable = getOldFeePayable(pricePurchaseDtl.getOrderlineId(), pricePurchase);
        PrepayBill oldPreBill = null;
        if (oldFeePayable != null) {
            oldPreBill = getOldPreBill(oldFeePayable.getId());
        }

        //应付账款
        Map<String, Object> addParam = new HashMap<>();
        // addParam.put("loadStatus", pricePurchaseAndDtlDTO.getLoadStatus());
        addParam.put("loadStatus", "0");
        addParam.put("orderlineId", pricePurchaseDtl.getOrderlineId());
        FeePayable feePayable = this.pricePurchaseToFeePayable(pricePurchase, pricePurchaseDtl, addParam);
        if (oldFeePayable != null) {
            // 发运时间
            if (oldFeePayable.getOrderDate() != null) {
                feePayable.setOrderDate(oldFeePayable.getOrderDate());
            }
            // OR号
            if (StringUtils.isEmpty(oldFeePayable.getWaybillDtlId())) {
                feePayable.setWaybillDtlId(oldFeePayable.getWaybillDtlId());
            }
            // 客户运单号
            if (StringUtils.isEmpty(oldFeePayable.getCusWaybill())) {
                feePayable.setCusWaybill(oldFeePayable.getCusWaybill());
            }
            // 业务主体
            if (StringUtils.isEmpty(oldFeePayable.getCiamsId())) {
                feePayable.setCiamsId(oldFeePayable.getCiamsId());
            }
        } else {
            feePayable.setCusWaybill(pricePurchaseAndDtlDTO.getCusWaybill());
            feePayable.setWaybillDtlId(pricePurchaseAndDtlDTO.getWaybillDtlId());
            feePayableService.insertOneFeePayable(feePayable);
        }

        // 生成预付账单
        createPrepayBill(feePayable, oldPreBill, pricePurchase, pricePurchaseDtl, false);
    }

    /**
     * 生成预付账单
     *
     * @param feePayable
     * @param oldPreBill
     * @param pricePurchase
     * @param pricePurchaseDtl
     */
    private void createPrepayBill(FeePayable feePayable, PrepayBill oldPreBill, PricePurchase pricePurchase,
                                  PricePurchaseDtl pricePurchaseDtl, boolean isHuiyunche) {
        //生成预付帐单
        PrepayBill prepayBill = new PrepayBill();
        BeanUtils.copyProperties(feePayable, prepayBill);
        prepayBill.setStatus(10);
        prepayBill.setGmtCreate(new Date());
        prepayBill.setHeadId(feePayable.getId());
        //设置承运商id和名称
        prepayBill.setLspId(feePayable.getPayerId());
        prepayBill.setLspName(feePayable.getPayerName());
        prepayBill.setPrepayOil(pricePurchaseDtl.getFirstOilTotal());
        prepayBill.setPrepayType(0);
        prepayBill.setCreator(new Long(1));
        // 2019-03-04 修改人送预付总额
        prepayBill.setPrepaySum(pricePurchaseDtl.getFirstOilTotal());
        prepayBill.setBalance(prepayBill.getPrepaySum());
        // prepayBill.setPertrolOilPrice(getPertrolOilPrice(pricePurchase.getVehicleClassifyId(), new Date()));
        prepayBill.setCurrentEffectDate(pricePurchaseDtl.getCurrentEffectDate());
        prepayBill.setCurrentOilPrice(pricePurchaseDtl.getCurrentOilPrice());
        if (oldPreBill != null) {
            prepayBill.setId(oldPreBill.getId());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(oldPreBill.getCusWaybill())) {
                prepayBill.setCusWaybill(oldPreBill.getCusWaybill());
            }
            prepayBillService.updateById(prepayBill);
        } else {
            if (isHuiyunche) {
                PrepayBill huiyunchePrepayBill = getHuiyunchePrepayBill(feePayable.getOrderCode(), feePayable.getWaybillDtlId());
                if (Objects.nonNull(huiyunchePrepayBill) && Objects.nonNull(huiyunchePrepayBill.getPertrolOilStatus())
                        && Integer.valueOf(1).equals(huiyunchePrepayBill.getPertrolOilStatus())) {
                    // 加油确认状态
                    prepayBill.setPertrolOilStatus(huiyunchePrepayBill.getPertrolOilStatus());
                    // 油价
                    prepayBill.setPertrolOilPrice(huiyunchePrepayBill.getPertrolOilPrice());
                    // 时间
                    prepayBill.setPertrolOilDate(huiyunchePrepayBill.getPertrolOilDate());
                }
            }
            prepayBillService.insert(prepayBill);
        }
    }

    /**
     * 获取已经存在的应付账款
     *
     * @param orderCode
     * @param pricePurchase
     * @return
     */
    private FeePayable getOldFeePayable(String orderCode, PricePurchase pricePurchase) {
        // 判断是否存在, 存在则生成
        EntityWrapper<FeePayable> feeEw = new EntityWrapper<>();
        // 指令号
        feeEw.eq("order_code", orderCode);
        feeEw.eq("vin", pricePurchase.getItemUid());
        feeEw.eq("waybill_id", pricePurchase.getShipmentCode());
        feeEw.eq("waybill_id", pricePurchase.getShipmentCode());
        feeEw.eq("order_dtl_id", pricePurchase.getShipOrderItemId());
        // 非取消状态
        feeEw.ne("status", 2);
        List<FeePayable> oldFeePayableList = feePayableService.selectListNoTenant(feeEw);
        if (!CollectionUtils.isEmpty(oldFeePayableList)) {
            return oldFeePayableList.get(0);
        }
        return null;
    }

    /**
     * 获取已经存在的预付账单
     *
     * @param headId
     * @return
     */
    private PrepayBill getOldPreBill(Long headId) {
        EntityWrapper<PrepayBill> prebillEw = new EntityWrapper<>();
        prebillEw.eq("head_id", headId);
        // 非取消状态
        prebillEw.ne("status", "40");
        List<PrepayBill> prepayBillList = prepayBillService.selectListNoTenant(prebillEw);
        if (!CollectionUtils.isEmpty(prepayBillList)) {
            return prepayBillList.get(0);
        }
        return null;
    }

    /**
     * 获取当前加油站油价
     *
     * @param vmCode
     * @return
     */
    @Override
    public BigDecimal getPertrolOilPrice(String vmCode, Date effctDate) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(vmCode)) {
            VehicleClassify vehicleClassify = vehicleClassifyService.getVehicleClassfyByVmCode(vmCode);
            if (vehicleClassify != null && vehicleClassify.getFuelTypeId() != null) {
                if (effctDate == null) {
                    effctDate = new Date();
                }
                PertrolPriceEffective pertrolPriceEffective = pertrolPriceEffectiveService.selectByEffectiveDateAndFuelTypeId(
                        vehicleClassify.getFuelTypeId(), effctDate);
                if (pertrolPriceEffective != null) {
                    return pertrolPriceEffective.getMarketPrice();
                }
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * 根据人送指令号生成账款信息
     *
     * @param orderCodeList
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void replenCreateFeePayableForSendDriver(List<String> orderCodeList) {
        if (!CollectionUtils.isEmpty(orderCodeList)) {
            orderCodeList.forEach(orderCode -> {
                PricePurchaseDtl pricePurchaseDtl = getPricePurchaseDtlByOrderCode(orderCode);
                if (Objects.nonNull(pricePurchaseDtl)) {
                    PricePurchase pricePurchase = getByHeadId(pricePurchaseDtl.getHeadId());
                    if (Objects.nonNull(pricePurchase)) {

                        EntityWrapper<FeePayable> feeEw = new EntityWrapper<>();
                        feeEw.eq("order_code", orderCode);
                        List<FeePayable> feePayableList = feePayableService.selectListNoTenant(feeEw);
                        if (CollectionUtils.isEmpty(feePayableList)) {
                            // 生成胀库
                            FeePayable feePayable = pricePurchaseToFeePayable(pricePurchase, pricePurchaseDtl, null);
                            feePayable.setOrderCode(orderCode);
                            feePayable.setLoadStatus("20");
                            updateOtherInfo(feePayable);
                            feePayableService.insertOneFeePayable(feePayable);
                            // 预付
                            createPrepayBill(feePayable, null, pricePurchase, pricePurchaseDtl, true);
                            // 计算价格
                            computePrice(pricePurchaseDtl, null);
                            // 推送OTM
                            putOtmSendPrice(pricePurchaseDtl, pricePurchase.getVehicleClassifyId());
                        }
                    }
                }
            });
        }
    }

    /**
     * 处理人送数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void dealSendPriceToFee() {
        EntityWrapper<PricePurchase> ew = new EntityWrapper<>();
        ew.eq("deal_flag", 0);
        ew.eq("is_delete", 0);
        ew.eq("create_from", "20");
        Page<PricePurchase> page = new Page<>(1, 100);
        List<PricePurchase> pricePurchaseList = baseMapper.selectPageNoTenant(page, ew);
        if (!CollectionUtils.isEmpty(pricePurchaseList)) {
            pricePurchaseList.forEach(price -> {
                this.dealHuiyuncheDuplcation(price.getWaybillDtlId());
                List<PricePurchaseDtl> dtlList = pricePurchaseDtlService.selectPricePurchaseDtlByHeadId(price.getId());
                if (!CollectionUtils.isEmpty(dtlList)) {
                    PricePurchaseDtl pricePurchaseDtl = dtlList.get(0);
                    EntityWrapper<FeePayable> feeEw = new EntityWrapper<>();
                    feeEw.eq("order_code", pricePurchaseDtl.getOrderlineId());
                    feeEw.ne("status", "2");
                    List<FeePayable> feePayableList = feePayableService.selectListNoTenant(feeEw);
                    if (CollectionUtils.isEmpty(feePayableList)) {
                        // 生成账款
                        FeePayable feePayable = pricePurchaseToFeePayable(price, pricePurchaseDtl, null);
                        feePayable.setOrderCode(pricePurchaseDtl.getOrderlineId());
                        feePayable.setLoadStatus("0");
                        // 更新发运时间和运单唯一标识等信息
                        updateOtherInfo(feePayable);
                        feePayableService.insertOneFeePayable(feePayable);
                        // 预付
                        createPrepayBill(feePayable, null, price, pricePurchaseDtl, true);
                        // 计算价格
                        computePrice(pricePurchaseDtl, null);
                        // 推送OTM
                        putOtmSendPrice(pricePurchaseDtl, price.getVehicleClassifyId());
                    }
                }
                price.setDealFlag(1);
            });

            this.updateBatchById(pricePurchaseList);
        }
    }

    /**
     * 删除慧运车已经存在的数据
     *
     * @param waybillDtlId
     */
    private void dealHuiyuncheDuplcation(String waybillDtlId) {
        if (!StringUtils.isEmpty(waybillDtlId)) {
            EntityWrapper<FeePayable> feeEw = new EntityWrapper<>();
            feeEw.eq("waybill_dtl_id", waybillDtlId);
            FeePayable feePayable = new FeePayable();
            feePayable.setStatus(2);
            feePayableService.update(feePayable, feeEw);
        }

    }

    /**
     * 获取未取消和未删除以及价格数据
     *
     * @param shipmentCode
     * @return
     */
    @Override
    public PricePurchase getPricePurchaseByShipmentCode(String shipmentCode) {
        if (!StringUtils.isEmpty(shipmentCode)) {
            EntityWrapper<PricePurchase> ew = new EntityWrapper<>();
            ew.eq("shipment_code", shipmentCode);
            ew.eq("is_delete", 0);
            List<PricePurchase> pricePurchaseList = baseMapper.selectListNoTenant(ew);
            if (!CollectionUtils.isEmpty(pricePurchaseList)) {
                return pricePurchaseList.get(0);
            }
        }
        return null;
    }

    /**
     * 重新推送otm价格到otm
     *
     * @param orderCodeList - 指令集合
     * @param isReCompute   - 是否重新计算价格
     */
    @Override
    public void repushHycPriceToOtm(List<String> orderCodeList, String isReCompute) {
        if (CollectionUtils.isEmpty(orderCodeList)) {
            throw new BaseException("请选择数据!");
        }
        if ("1".equals(isReCompute)) {
            // 重新计算价格
            List<HycOrderData> dataList = hycApiUtil.getHycDataByOrderCode(orderCodeList);
            if (!CollectionUtils.isEmpty(dataList)) {
                Set<String> dwaybillIdSet = Sets.newHashSet();
                dataList.forEach(data -> {
                    dwaybillIdSet.add(data.getId());
                });
                // 重新推送
                hycApiUtil.reComputePriceToOtm(dwaybillIdSet);
            }
        } else {
            // 不计价, 直接推送
            orderCodeList.forEach(orderCode -> {
                EntityWrapper<PricePurchaseVO> ew = new EntityWrapper<>();
                ew.eq("orderlineId", orderCode);
                ew.orderBy("id desc");
                List<PricePurchaseDtl> pricePurchaseDtlList = pricePurchaseDtlMapper.getUpdatePriceDtlNoTenant(ew);
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(pricePurchaseDtlList)) {
                    PricePurchaseDtl pricePurchaseDtl = pricePurchaseDtlList.get(0);
                    Long headId = pricePurchaseDtl.getHeadId();
                    EntityWrapper<PricePurchase> priceEw = new EntityWrapper<>();
                    priceEw.eq("id", headId);
                    List<PricePurchase> pricePurchaseList = baseMapper.selectListNoTenant(priceEw);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(pricePurchaseList)) {
                        PricePurchase pricePurchase = pricePurchaseList.get(0);
                        String oilType = null;
                        if (!StringUtils.isEmpty(pricePurchase.getVehicleClassifyId())) {
                            List<FuelType> fuelTypeList = fuelTypeMapper.getFuelTypeByVehicleId(pricePurchase.getVehicleClassifyId());
                            if (!org.springframework.util.CollectionUtils.isEmpty(fuelTypeList)) {
                                oilType = fuelTypeList.get(0).getFuelName();
                            }
                        }
                        BmsServiceResult bmsServiceResult = otmUtil.getSavePriceByRs(pricePurchaseDtl, oilType);
                        LOGGER.info("repushHycPriceToOtm 返回结果: {}", bmsServiceResult.toString());
                    }
                }
            });
        }
    }

    private PrepayBill getHuiyunchePrepayBill(String orderCode, String waybillDtlId) {
        EntityWrapper<PrepayBill> ew = new EntityWrapper<>();
        ew.eq("order_code", orderCode);
        if (!StringUtils.isEmpty(waybillDtlId)) {
            ew.eq("waybill_dtl_id", waybillDtlId);
        }
        List<PrepayBill> prepayBillList = prepayBillService.selectListNoTenant(ew);
        if (!CollectionUtils.isEmpty(prepayBillList)) {
            return prepayBillList.get(0);
        }
        return null;
    }

    /**
     * 人送其他信息的补充
     *
     * @param feePayable
     */
    private void updateOtherInfo(FeePayable feePayable) {
        ShipmentDTO otmShipment = otmUtil.getOtmShipment(feePayable.getOrderCode());
        if (otmShipment != null && !CollectionUtils.isEmpty(otmShipment.getShipTaskDTOList())) {
            // // 发运时间
            // if (feePayable.getOrderDate() == null && otmShipment.getExpcetShipDate() != null) {
            //     feePayable.setOrderDate(otmShipment.getExpcetShipDate());
            // }
            for (ShipTaskDTO shipTaskDTO : otmShipment.getShipTaskDTOList()) {
                if (shipTaskDTO.getVin() != null && shipTaskDTO.getVin().equals(feePayable.getVin())) {
                    // OR号
                    if (!StringUtils.isEmpty(shipTaskDTO.getTaskId())) {
                        feePayable.setWaybillDtlId(shipTaskDTO.getTaskId());
                    }
                    // 客户运单号
                    if (!StringUtils.isEmpty(shipTaskDTO.getCusWaybillNo())) {
                        feePayable.setCusWaybill(shipTaskDTO.getCusWaybillNo());
                    }
                    // 业务主体
                    if (!StringUtils.isEmpty(shipTaskDTO.getCiamsId())) {
                        feePayable.setCiamsId(shipTaskDTO.getCiamsId());
                    }
                    continue;
                }
            }
        }
    }

    /**
     * 获取价格主表数据
     *
     * @param headId
     * @return
     */
    private PricePurchase getByHeadId(Long headId) {
        EntityWrapper<PricePurchase> headEw = new EntityWrapper<>();
        headEw.eq("id", headId);
        List<PricePurchase> pricePurchaseList = baseMapper.selectListNoTenant(headEw);
        if (!CollectionUtils.isEmpty(pricePurchaseList)) {
            return pricePurchaseList.get(0);
        }
        return null;
    }

    /**
     * 根据指令获取最新的数据
     *
     * @param orderCode
     * @return
     */
    private PricePurchaseDtl getPricePurchaseDtlByOrderCode(String orderCode) {
        EntityWrapper<PricePurchaseDtl> ew = new EntityWrapper<>();
        ew.eq("orderlineId", orderCode);
        ew.orderBy("id desc");
        List<PricePurchaseDtl> dtlList = pricePurchaseDtlMapper.selectListNoTenant(ew);
        if (!CollectionUtils.isEmpty(dtlList)) {
            return dtlList.get(0);
        }
        return null;
    }

    /**
     * 获取当前油价
     *
     * @param vmCode
     * @return
     */
    private BigDecimal getFuelOilPrice(String vmCode, Date effctDate) {
        if (org.apache.commons.lang3.StringUtils.isNotBlank(vmCode)) {
            VehicleClassify vehicleClassify = vehicleClassifyService.getVehicleClassfyByVmCode(vmCode);
            if (vehicleClassify != null && vehicleClassify.getFuelTypeId() != null) {
                if (effctDate == null) {
                    effctDate = new Date();
                }
                FuelPriceEffective fuelPriceEffective = fuelPriceEffectiveService.selectByEffectiveDateAndFuelTypeId(
                        vehicleClassify.getFuelTypeId(), effctDate);
                if (fuelPriceEffective != null) {
                    return fuelPriceEffective.getMarketPrice();
                }
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * 将支付价格信息转换成应付账款
     *
     * @return
     */
    private FeePayable pricePurchaseToFeePayable(PricePurchase pricePurchase, PricePurchaseDtl pricePurchaseDtl, Map<String, Object> addParam) {
        FeePayable feePayable = new FeePayable();
//        BeanUtils.copyProperties(pricePurchase,feePayable);
        feePayable.setWaybillId(pricePurchase.getShipmentCode());
        feePayable.setOrderDtlId(pricePurchase.getShipOrderItemId());
        feePayable.setVin(pricePurchase.getItemUid());
        feePayable.setPayerId(pricePurchase.getLspId());
        feePayable.setPayerName(pricePurchase.getLspName());
        feePayable.setPayeeId(pricePurchase.getFleetId());
        feePayable.setPayeeName(pricePurchase.getFleetName());
        feePayable.setFleetId(pricePurchase.getFleetId());
        feePayable.setFleetName(pricePurchase.getFleetName());
        feePayable.setDriverId(pricePurchase.getDriverId());
        feePayable.setDriverName(pricePurchase.getDriverName());
        // 车型分类id
        feePayable.setVehicleClassifyId(pricePurchase.getVehicleClassifyId());
        feePayable.setVehicleTypeCode(pricePurchase.getVehicleTypeCode());

        feePayable.setStartAddr(pricePurchase.getDepartAdressName());
        feePayable.setStartProvince(pricePurchase.getStartProvince());
        feePayable.setStartCity(pricePurchase.getStartCity());
        feePayable.setStartCounty(pricePurchase.getStartCounty());

        feePayable.setEndAddr(pricePurchase.getDestAdderssName());
        feePayable.setEndProvince(pricePurchase.getEndProvince());
        feePayable.setEndCity(pricePurchase.getEndCity());
        feePayable.setEndCounty(pricePurchase.getEndCounty());

        EntityWrapper<PricePurchase> feePayableEntityWrapper = new EntityWrapper<>();
        feePayableEntityWrapper.eq("id", pricePurchase.getId());
        // feePayable.setActualPrice(baseMapper.selectEndCityForCurrentValueByPriceNoTenant(feePayableEntityWrapper));
        feePayable.setCashBaPay(pricePurchaseDtl.getServiceWage());
        feePayable.setOilBaPay(pricePurchaseDtl.getCardOilTotal());

        if (pricePurchase.getTransTypeId() != null) {
            feePayable.setTransTypeId(pricePurchase.getTransTypeId());
            TransportationTypeDTO transportTypeById = mdmUtil.getTransportTypeById(pricePurchase.getTransTypeId());
            if (transportTypeById != null) {
                feePayable.setTransTypeName(transportTypeById.getOtmValue());
            }
        }
        if (!CollectionUtils.isEmpty(addParam)) {
            feePayable.setLoadStatus(addParam.get("loadStatus") == null ? "" : addParam.get("loadStatus").toString());
            feePayable.setOrderCode(addParam.get("orderlineId") == null ? "" : addParam.get("orderlineId").toString());
        }
        if (Strings.isNullOrEmpty(feePayable.getEndAddr())) {
            feePayable.setEndAddr(
                    Strings.nullToEmpty(feePayable.getEndProvince()) +
                            Strings.nullToEmpty(feePayable.getEndCity()) +
                            Strings.nullToEmpty(feePayable.getEndCounty())
            );
        }
        feePayable.setEstAmt(pricePurchase.getExtPurchasePrice() == null ? BigDecimal.ZERO : pricePurchase.getExtPurchasePrice());
        feePayable.setActualAmt(pricePurchase.getActPurchasePrice() == null ? BigDecimal.ZERO : pricePurchase.getActPurchasePrice());
        feePayable.setKilometre(pricePurchase.getMileage() == null ? BigDecimal.ZERO : pricePurchase.getMileage());

        feePayable.setEstPrice(feePayable.getEstAmt().divide(feePayable.getKilometre(), BigDecimal.ROUND_HALF_UP));
        feePayable.setActualPrice(feePayable.getActualAmt().divide(feePayable.getKilometre(), BigDecimal.ROUND_HALF_UP));
        // 客户运单号
        feePayable.setCusWaybill(pricePurchase.getCusWaybill());
        // OR号
        feePayable.setWaybillDtlId(pricePurchase.getWaybillDtlId());
        feePayable.setTenantId(pricePurchase.getTenantId());
        return feePayable;
    }

    /**
     * 批量更新支付价格
     *
     * @param pricePurchases
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> updatePurchases(List<PricePurchase> pricePurchases) {
        LOGGER.info("PricePurchaseServiceImpl.updatePurchase InParam:" + pricePurchases);
        List<String> msg = Lists.newArrayList();
        pricePurchases.forEach(pricePurchase -> {
            try {
                if (Objects.isNull(pricePurchase.getId())) {
                    throw new BaseException("无法获取修改的信息");
                }
                if (Objects.isNull(pricePurchase.getActPurchasePrice())) {
                    throw new BaseException("请填写支付价格");
                }
                //更新溢价比
                updateOverflowRate(this.selectById(pricePurchase), null, pricePurchase.getActPurchasePrice());
            } catch (BaseException e) {
                LOGGER.error("PricePurchaseServiceImpl.updatePurchase ERROR: {}", e.getMessage());
                msg.add("支付价格:" + "" + ":" + e.getMessage());
            } catch (Exception e) {
                LOGGER.error("PricePurchaseServiceImpl.updatePurchase ERROR: {}", e.getMessage());
                msg.add("支付价格:" + "" + ":" + "修改失败");
            }
        });
        return msg;
    }

    /**
     * 根据运输任务更新数据所有列数据
     *
     * @param pricePurchase
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateOrInsertPurchaseByShipTask(PricePurchase pricePurchase) {
        if (Objects.isNull(pricePurchase.getShipTaskCode())) {
            throw new BaseException("运输任务编号不存在");
        }
        //根据运单号和详明信息获取对应信息
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("ship_task_code", pricePurchase.getShipTaskCode());
        entityWrapper.eq("item_uid", pricePurchase.getItemUid());
        List<PricePurchase> pricePurchases = baseMapper.selectList(entityWrapper);
        //若存在指定运单号信息进行修改，若不存在进行新增
        if (!CollectionUtils.isEmpty(pricePurchases)) {
            //存在该运输任务号
            //拦截生效状态的修改请求
            if (pricePurchases.get(0).getEnable()) {
                throw new BaseException("该信息已经生效，无法修改");
            }
            if (pricePurchase.getEnable()) {
                throw new BaseException("该信息已经生效，无法修改");
            }
            Integer returnVal = baseMapper.update(pricePurchase, entityWrapper);
            this.updateOverflowRate(pricePurchase, null, pricePurchase.getActPurchasePrice());
            return returnVal;
        } else {
            //修改绑定登陆信息
            if (Objects.isNull(pricePurchase.getLspId())) {
                throw new BaseException("请绑定承运商");
            }
            new AccountBindUtil<PricePurchase>().bindCreatorAndTenantId(pricePurchase, false);
            //新增并附加溢价比结果
            Integer returnVal = baseMapper.insert(pricePurchase);
            this.updateOverflowRate(pricePurchase, null, pricePurchase.getActPurchasePrice());
            return returnVal;
        }
    }

    /**
     * 根据车架号修改暂估价
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateExtPurchasePriceByItemUidNoTenant(FeePayable feePayable) {
        try {
            EntityWrapper<PricePurchase> entityWrapper = new EntityWrapper<PricePurchase>();
            entityWrapper.eq("item_uid", feePayable.getVin());
            List<PricePurchase> list = baseMapper.selectListNoTenant(entityWrapper);
            PricePurchase pricePurchase = null;
            if (!CollectionUtils.isEmpty(list)) {
                pricePurchase = list.get(list.size() - 1);
            }
            if (pricePurchase != null) {
                pricePurchase.setExtPurchasePrice(feePayable.getEstPrice());
                BigDecimal actualPrice = feePayable.getActualPrice();
                boolean updateActual = !(actualPrice == null || actualPrice.compareTo(BigDecimal.ZERO) <= 0);
                if (updateActual) {
                    pricePurchase.setActPurchasePrice(actualPrice);
                } else {
                    actualPrice = BigDecimal.ZERO;
                }
                updateById(pricePurchase);

                if (updateActual) {
                    //获取财务系数，推送OTM
                    pushPriceToOtm(actualPrice, feePayable.getOilFill(), pricePurchase.getLspId(), feePayable.getWaybillDtlId(),
                            feePayable.getKilometre(), feePayable.getTransTypeName(), feePayable.getActualAmt());
                    //BigDecimal fiRate = null;
                    //PriceFiRate priceFiRate = priceFiRateService.queryPriceFiRateById(pricePurchase.getLspId());
                    ////使用获取的财务系数，如不存在默认1
                    //if (Objects.nonNull(priceFiRate) && Objects.nonNull(priceFiRate.getFiRate())) {
                    //    fiRate = priceFiRate.getFiRate().setScale(2, BigDecimal.ROUND_HALF_UP);
                    //} else {
                    //    fiRate = new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //}
                    //BigDecimal price = actualPrice.multiply(fiRate).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //
                    //EntityWrapper ew = new EntityWrapper();
                    //ew.eq("item_source_key", feePayable.getWaybillDtlId());
                    //PriceIncoming incoming = new PriceIncoming();
                    //incoming.setActIncomingPrice(price);
                    //boolean updateResult = priceIncomingService.update(incoming, ew);
                    ////根据运输订单号，开始向OTM系统推送执行价格
                    //RestfulResponse<String> otmResult = otmUtil.exportPrice(feePayable.getWaybillDtlId(), price, feePayable.getKilometre(), "");
                    //if (Objects.isNull(otmResult)) {
                    //    throw new BaseException("向中联结算系统推送价格失败！");
                    //} else if (otmResult.getCode() != 0) {
                    //    throw new BaseException(otmResult.getMessage());
                    //}
                } else {
                    // 在没有我们价格表中找到的时候根据账款推送价格
                    pushPriceToOtm(feePayable.getActualPrice(), feePayable.getOilFill(), feePayable.getPayerId(), feePayable.getWaybillDtlId(),
                            feePayable.getKilometre(), feePayable.getTransTypeName(), feePayable.getActualAmt());
                }
            } else {
                pushPriceToOtm(feePayable.getActualPrice(), feePayable.getOilFill(), null, feePayable.getWaybillDtlId(),
                        feePayable.getKilometre(), feePayable.getTransTypeName(), feePayable.getActualAmt());
            }
        } catch (BaseException e) {
            LOGGER.error("PricePurchaseServiceImpl.updateExtPurchasePriceByItemUidNoTenant error: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("PricePurchaseServiceImpl.updateExtPurchasePriceByItemUidNoTenant error: {}", e.getMessage());
            throw new BaseException("车架号修改支付价格失败");
        }
    }

    /**
     * 推送价格
     *
     * @param actualPrice
     * @param oilFill
     * @param lspId
     * @param waybillDtlId
     * @param kilometre
     * @param transformName
     * @param actualAmt
     */
    private void pushPriceToOtm(BigDecimal actualPrice, BigDecimal oilFill, Long lspId, String waybillDtlId,
                                BigDecimal kilometre, String transformName, BigDecimal actualAmt) {
        //获取财务系数，推送OTM
        // BigDecimal fiRate = null;
        // PriceFiRate priceFiRate = priceFiRateService.queryPriceFiRateById(lspId);
        // //使用获取的财务系数，如不存在默认1
        // if (Objects.nonNull(priceFiRate) && Objects.nonNull(priceFiRate.getFiRate())) {
        //     fiRate = priceFiRate.getFiRate().setScale(2, BigDecimal.ROUND_HALF_UP);
        // } else {
        //     fiRate = new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP);
        // }
        // BigDecimal fiRate = getRateByTransform(transformName);
        // 2019-06-06修改 不区分运输方式, 统一使用 1.062 比例系数
        BigDecimal fiRate = RateTransformEnum.OTHER_RATE.getRate();
        // 2019-05-13 修改, 推送价格在合同价基础上累加油补, 最后乘以比例后推送
        // 2019-07-04 修改, 用总金额 + 油补 + 其他费用后除以公里数的新单价推送
        if (Objects.nonNull(oilFill)) {
            actualAmt = actualAmt.add(oilFill);
        }
        actualPrice = actualAmt.divide(kilometre, 6, BigDecimal.ROUND_HALF_UP).setScale(4, BigDecimal.ROUND_HALF_UP);

        BigDecimal price = actualPrice.multiply(fiRate).setScale(4, BigDecimal.ROUND_HALF_UP);

        EntityWrapper ew = new EntityWrapper();
        ew.eq("item_source_key", waybillDtlId);
        PriceIncoming incoming = new PriceIncoming();
        incoming.setActIncomingPrice(price);
        priceIncomingService.update(incoming, ew);
        //根据运输订单号，开始向OTM系统推送执行价格
        RestfulResponse<String> otmResult = otmUtil.exportPrice(waybillDtlId, price, kilometre, "");
        if (Objects.isNull(otmResult)) {
            throw new BaseException("向中联结算系统推送价格失败！");
        } else if (otmResult.getCode() != 0) {
            throw new BaseException(otmResult.getMessage());
        }
    }

    /**
     * 根据运输方式获取对应的系数
     *
     * @param transform
     * @return
     */
    private BigDecimal getRateByTransform(String transform) {
        BigDecimal rate = BigDecimal.ONE;
        if (!StringUtils.isEmpty(transform)) {
            if (RateTransformEnum.SEND_DRIVER_RATE.getTransform().equals(transform)) {
                return RateTransformEnum.SEND_DRIVER_RATE.getRate();
            } else {
                return RateTransformEnum.OTHER_RATE.getRate();
            }
        }
        return rate;
    }

    /**
     * 根据运输任务更新exlel导入数据
     *
     * @param pricePurchase
     * @return
     */
    @Override
    public void updatePurchaseExlByShipTask(PricePurchase pricePurchase) {
        if (Objects.isNull(pricePurchase.getShipTaskCode())) {
            throw new BaseException("运输任务编号不存在");
        }
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("ship_task_code", pricePurchase.getShipTaskCode());
        entityWrapper.eq("item_uid", pricePurchase.getItemUid());
        List<PricePurchase> pricePurchases = baseMapper.selectList(entityWrapper);
        if (!CollectionUtils.isEmpty(pricePurchases)) {
            //存在该运输任务号
            //拦截生效状态的修改请求
            if (Objects.nonNull(pricePurchases.get(0)) && pricePurchases.get(0).getEnable()) {
                throw new BaseException("该信息已经生效，无法修改");
            }
            this.updateOverflowRate(pricePurchases.get(0), null, pricePurchase.getActPurchasePrice());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer deletePurchaseByShipOrderItemId(PricePurchase pricePurchasePram) {
        //获取对应运单号信息
        EntityWrapper entityWrapper = new EntityWrapper();
        if (Strings.isNullOrEmpty(pricePurchasePram.getShipmentCode())) {
            pricePurchasePram.setShipmentCode("");
        } else {
            entityWrapper.eq("shipment_code", pricePurchasePram.getShipmentCode());
        }
        if (!Strings.isNullOrEmpty(pricePurchasePram.getShipTaskCode())) {
            entityWrapper.eq("ship_task_code", pricePurchasePram.getShipTaskCode());
        }
        if (Objects.nonNull(pricePurchasePram.getShipOrderItemId())) {
            entityWrapper.eq("ship_order_item_id", pricePurchasePram.getShipOrderItemId());
        }
        List<PricePurchase> pricePurchase = baseMapper.selectListNoTenant(entityWrapper);
        List<Long> pricePurchaseIds = new ArrayList<>();
        List<String> shipmentCodes = new ArrayList<>();
        // if (CollectionUtils.isEmpty(pricePurchase)) throw new BaseException("信息不存在");
        //验证存在数据
        Integer integer = null;
        if (!CollectionUtils.isEmpty(pricePurchase)) {

            for (PricePurchase item : pricePurchase) {
                if (!item.getEnable()) {
                    throw new BaseException(pricePurchasePram.getShipmentCode() + "价格已失效无法删除");
                }
                pricePurchaseIds.add(item.getId());
                shipmentCodes.add(item.getShipmentCode());
            }
            if (!CollectionUtils.isEmpty(pricePurchaseIds)) {
                integer = baseMapper.deleteBatchIds(pricePurchaseIds);
            }
        }

        if (!StringUtils.isEmpty(pricePurchasePram.getShipmentCode())) {
            EntityWrapper<FeePayable> feePayableEntityWrapper = new EntityWrapper<>();
            FeePayable feePayable = new FeePayable();
            // 已经取消
            feePayable.setStatus(2);
            feePayableEntityWrapper.eq("waybill_id", pricePurchasePram.getShipmentCode());
            feePayableService.update(feePayable, feePayableEntityWrapper);

            EntityWrapper<PrepayBill> prepayBillEntityWrapper = new EntityWrapper<>();
            PrepayBill prepayBill = new PrepayBill();
            prepayBill.setStatus(40);
            prepayBillEntityWrapper.eq("waybill_id", pricePurchasePram.getShipmentCode());
            prepayBillService.update(prepayBill, prepayBillEntityWrapper);
        }
        return integer;
    }


    /**
     * 生效支付价格
     *
     * @param id
     * @param token
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enablePurchase(Long id, String token) {
        PricePurchase pricePurchase = baseMapper.selectById(id);
        //验证数据
        if (Objects.isNull(pricePurchase)) {
            throw new BaseException("指定生效信息不存在");
        }
        if (pricePurchase.getEnable() != null && pricePurchase.getEnable()) {
            throw new BaseException("该条已生效请选择其他信息");
        }
        if (pricePurchase.getExtPurchasePrice() == null) {
            throw new BaseException("暂估价为空");
        }
        //设置执行价和生效状态进行改动
        PricePurchase pricePurchase1 = new PricePurchase();
        if (Objects.isNull(pricePurchase.getActPurchasePrice())) {
            BigDecimal deductRate = null;
            //设置支付扣点，没有返回默认使用1
            PriceDeductRate priceDeductRate = priceDeductRateService.returnPriceDeductRate(pricePurchase.getLspId(), pricePurchase.getFleetId());
            if (Objects.nonNull(priceDeductRate) && Objects.nonNull(priceDeductRate.getRate())) {
                deductRate = priceDeductRate.getRate().setScale(2, BigDecimal.ROUND_HALF_UP);
            } else {
                deductRate = new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            pricePurchase1.setActPurchasePrice(pricePurchase.getExtPurchasePrice().multiply(deductRate).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        pricePurchase1.setEnable(true);
        pricePurchase1.setId(id);
        baseMapper.updateById(pricePurchase1);


        //获取最新数据进行应收价格计算
        pricePurchase = baseMapper.selectById(id);

        //创建应付账款
//        feePayableService.insertFeePayable(pricePurchase, token);

        //设置财务系数
        BigDecimal fiRate = null;
        PriceFiRate priceFiRate = priceFiRateService.queryPriceFiRateById(pricePurchase.getLspId());
        //使用获取的财务系数，如不存在默认1
        if (Objects.nonNull(priceFiRate) && Objects.nonNull(priceFiRate.getFiRate())) {
            fiRate = priceFiRate.getFiRate().setScale(2, BigDecimal.ROUND_HALF_UP);
        } else {
            fiRate = new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP);
        }

        BigDecimal price;
//        if ("10".equals(pricePurchase.getCreateFrom())) {
        //线路价格
        BigDecimal simglePrice = this.getSingleKilometrePurchasePrice(pricePurchase);
        if (Objects.isNull(simglePrice)) {
            simglePrice = pricePurchase.getActPurchasePrice();
        }
        price = simglePrice.multiply(fiRate).setScale(2, BigDecimal.ROUND_HALF_UP);

        if (pricePurchase.getMileage() == null) {
            pricePurchase.setMileage(new BigDecimal(1));
        }
//        } else {
//            price = pricePurchase.getExtPurchasePrice().multiply(fiRate);
//            pricePurchase.setMileage(new BigDecimal(1));
//        }
        priceIncomingService.updateIncomingPriceByTaskCode(pricePurchase.getShipTaskCode(), pricePurchase.getShipOrderItemId(), price, pricePurchase.getMileage(), token);
    }

    /**
     * 根据运单货物明细ID查询
     *
     * @param shipOrderItemId
     * @return
     */
    @Override
    public PricePurchase queryPricePurchase(Long shipOrderItemId) {
        PricePurchase cn = null;
        Wrapper<PricePurchase> ew = new EntityWrapper<>();
        if (shipOrderItemId != null) {
            ew.eq("ship_order_item_id", shipOrderItemId);
            cn = this.selectOne(ew);
        }
        return cn;
    }

    /**
     * 修改人送价格
     *
     * @param pricePurchaseVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateSendDriverPurchasePrice(PricePurchaseVO pricePurchaseVO) {
        // 根据指令号和车架号获取价格主表 -> 再根据送车证号
        EntityWrapper<PricePurchaseVO> ew = new EntityWrapper<>();
        // 指令号
        ew.eq("orderlineId", pricePurchaseVO.getOrderCode());
        ew.eq("item_uid", pricePurchaseVO.getVin());
        ew.eq("vcorderno", pricePurchaseVO.getVcorderno());
        ew.orderBy("id desc");
        List<PricePurchaseDtl> pricePurchaseDtlList = pricePurchaseDtlMapper.getUpdatePriceDtlNoTenant(ew);
        if (!CollectionUtils.isEmpty(pricePurchaseDtlList)) {
            PricePurchaseDtl pricePurchaseDtl = pricePurchaseDtlList.get(0);
            // 油价
            pricePurchaseDtl.setOilPrice(pricePurchaseVO.getOilPrice());
            // 第一桶油量
            pricePurchaseDtl.setFirstOilCapacity(pricePurchaseVO.getFirstOilCapacity());
            // 第一桶油费
            pricePurchaseDtl.setFirstOilTotal(pricePurchaseVO.getFirstOilTotal());
            // 总运费
            pricePurchaseDtl.setSumCost(pricePurchaseVO.getSumCost());
            // 公里数
            pricePurchaseDtl.setKilometer(pricePurchaseVO.getKilometer());
            // 应充卡油费
            pricePurchaseDtl.setCardOilTotal(pricePurchaseVO.getCardOilTotal());
            // 应充卡油量
            pricePurchaseDtl.setCardOilCapacity(pricePurchaseVO.getCardOilCapacity());
            // 司机编号
            pricePurchaseDtl.setVcorderno(pricePurchaseVO.getVcorderno());
            // 发运时间
            pricePurchaseDtl.setCurrentEffectDate(pricePurchaseVO.getCurrentEffectDate());
            // 劳务价
            pricePurchaseDtl.setServiceWage(pricePurchaseVO.getServiceWage());
            // 当前市场油价
            pricePurchaseDtl.setCurrentOilPrice(pricePurchaseVO.getCurrentOilPrice());
            // 总油费
            pricePurchaseDtl.setOilCost(pricePurchaseVO.getOilCost());
            pricePurchaseDtlService.updateById(pricePurchaseDtl);

            // 更新更新价格主表
            PricePurchase pricePurchase = new PricePurchase();
            pricePurchase.setId(pricePurchaseDtl.getHeadId());
            pricePurchase.setActPurchasePrice(pricePurchaseDtl.getSumCost() == null ? BigDecimal.ZERO : pricePurchaseDtl.getSumCost());
            pricePurchase.setMileage(pricePurchaseDtl.getKilometer());
            this.updateById(pricePurchase);

            // 计算价格
            PricePurchaseDtl computePriceDtl = new PricePurchaseDtl();
            BeanUtils.copyProperties(pricePurchaseDtl, computePriceDtl);
            computePrice(computePriceDtl, null);
            // 推送OTM
            putOtmSendPrice(computePriceDtl, pricePurchase.getVehicleClassifyId());

            // 更新应付账款
            EntityWrapper<FeePayable> feePayableEntityWrapper = new EntityWrapper<>();
            feePayableEntityWrapper.eq("order_code", pricePurchaseVO.getOrderCode());
            // feePayableEntityWrapper.eq("vin", pricePurchaseVO.getVin());
            FeePayable updateFeePayable = new FeePayable();
            updateFeePayable.setCashBaPay(pricePurchaseDtl.getServiceWage());
            updateFeePayable.setOilBaPay(pricePurchaseDtl.getCardOilTotal());
            // 公里数
            updateFeePayable.setKilometre(pricePurchaseDtl.getKilometer());
            // 总金额
            updateFeePayable.setActualAmt(pricePurchaseDtl.getSumCost());
            // 单价
            updateFeePayable.setActualPrice(updateFeePayable.getActualAmt().divide(updateFeePayable.getKilometre(), BigDecimal.ROUND_HALF_UP));
            feePayableService.update(updateFeePayable, feePayableEntityWrapper);


            // 更新预付账单
            EntityWrapper<PrepayBill> billEntityWrapper = new EntityWrapper<>();
            billEntityWrapper.eq("order_code", pricePurchaseVO.getOrderCode());
            PrepayBill updatePrepaybill = new PrepayBill();
            updatePrepaybill.setPrepayOil(pricePurchaseDtl.getFirstOilTotal());
            updatePrepaybill.setPrepaySum(pricePurchaseDtl.getFirstOilTotal());
            updatePrepaybill.setCurrentEffectDate(pricePurchaseDtl.getCurrentEffectDate());
            updatePrepaybill.setCurrentOilPrice(pricePurchaseDtl.getCurrentOilPrice());
            // 公里数
            updatePrepaybill.setKilometre(pricePurchaseDtl.getKilometer());
            // 总金额
            updatePrepaybill.setActualAmt(pricePurchaseDtl.getSumCost());
            // 单价
            updatePrepaybill.setActualPrice(updateFeePayable.getActualPrice());
            prepayBillService.update(updatePrepaybill, billEntityWrapper);
        }
    }

    /**
     * 获取慧运车需要的信息
     *
     * @param voList
     * @return
     */
    @Override
    public List<FeePayableVO> getHunyuncheInfo(List<FeePayableVO> voList) {
        if (!CollectionUtils.isEmpty(voList)) {
            // voList
            voList.stream().filter(vo -> vo.getId() != null).forEach(vo -> {
                FeePayable feePayable = feePayableService.selectById(vo.getId());
                EntityWrapper<PricePurchaseDetailVO> priceDtlEw = new EntityWrapper<>();
                priceDtlEw.eq("orderlineId", feePayable.getOrderCode());
                priceDtlEw.eq("shipment_code", feePayable.getWaybillId());
                priceDtlEw.eq("item_uid", feePayable.getVin());
                List<PricePurchaseDetailVO> pricePurchaseDetailVOList = pricePurchaseDtlMapper.getPricePurchaseDetail(priceDtlEw);
                if (!CollectionUtils.isEmpty(pricePurchaseDetailVOList)) {
                    PricePurchaseDetailVO pricePurchaseDetailVO = pricePurchaseDetailVOList.get(0);
                    // firstOilTotal  第一桶油费
                    vo.setFirstOilTotal(pricePurchaseDetailVO.getFirstOilTotal());
                    // firstOilCapacity  第一桶油量
                    vo.setFirstOilCapacity(pricePurchaseDetailVO.getFirstOilCapacity());
                    // 当前市场油价
                    vo.setCurrentOilPrice(pricePurchaseDetailVO.getCurrentOilPrice());
                }
            });
        }
        return voList;
    }


    /**
     * 获取上个最高执行价
     *
     * @param pricePurchase
     * @return
     */
    private BigDecimal getSingleKilometrePurchasePrice(PricePurchase pricePurchase) {
        try {
            BigDecimal maxPurchasePrice = null;
            //若存在执行价信息进行价格计算
            if (Objects.nonNull(pricePurchase)) {
                maxPurchasePrice = new BigDecimal(0);
                //获取当前执行价的生效时间的上个月的执行价
                DateTime gmtTime = new DateTime(pricePurchase.getGmtModify());
                //上个月
                EntityWrapper ew = new EntityWrapper();
                DateTime lastMonthTime = gmtTime.minusMonths(1);
                EntityWrapper lastMonthEw = new EntityWrapper();
                lastMonthEw.eq("is_enable", "1");
                lastMonthEw.ge("gmt_modify", lastMonthTime.dayOfMonth().withMinimumValue().toString("yyyy-MM-dd"));
                lastMonthEw.le("gmt_modify", lastMonthTime.dayOfMonth().withMaximumValue().toString("yyyy-MM-dd"));
                lastMonthEw.eq("trans_type_id", pricePurchase.getTransTypeId());
                lastMonthEw.andNew().eq("depart_location_ad_code", pricePurchase.getDepartLocationAdCode()).or().eq("depart_adress_name", pricePurchase.getDepartAdressName());
                lastMonthEw.andNew().eq("dest_location_ad_code", pricePurchase.getDestLocationAdCode()).or().eq("dest_adderss_name", pricePurchase.getDestAdderssName());
                List<PricePurchase> pricePurchases = baseMapper.selectList(lastMonthEw);
                //寻找最大价格
                for (PricePurchase pricePurchaseItem :
                        pricePurchases) {
                    BigDecimal actPurchase = pricePurchaseItem.getActPurchasePrice();
                    //maxPurchasePrice<=actPurchase
                    if (maxPurchasePrice.compareTo(actPurchase) < 0) {
                        maxPurchasePrice = actPurchase;
                    }
                }
                //最大值为初始值
                if (maxPurchasePrice.compareTo(new BigDecimal(0)) == 0) {
                    //获取本月数据
                    EntityWrapper nowMonthEw = new EntityWrapper();
                    nowMonthEw.eq("is_enable", "1");
                    nowMonthEw.ge("gmt_modify", gmtTime.dayOfMonth().withMinimumValue().toString("yyyy-MM-dd"));
                    nowMonthEw.le("gmt_modify", gmtTime.dayOfMonth().withMaximumValue().toString("yyyy-MM-dd"));
                    nowMonthEw.eq("trans_type_id", pricePurchase.getTransTypeId());
                    nowMonthEw.andNew().eq("depart_location_ad_code", pricePurchase.getDepartLocationAdCode()).or().eq("depart_adress_name", pricePurchase.getDepartAdressName());
                    nowMonthEw.andNew().eq("dest_location_ad_code", pricePurchase.getDestLocationAdCode()).or().eq("dest_adderss_name", pricePurchase.getDestAdderssName());
                    List<PricePurchase> pricePurchasesNowMonth = baseMapper.selectList(nowMonthEw);
                    //如果有数据使用本月第一条
                    if (!CollectionUtils.isEmpty(pricePurchasesNowMonth)) {
                        maxPurchasePrice = pricePurchasesNowMonth.get(0).getActPurchasePrice();
                    }
                }
            }
            return maxPurchasePrice;
        } catch (Exception e) {
            LOGGER.error("PricePurchaseServiceImpl.getSingleKilometrePurchasePrice error: {}", e.getMessage());
            throw new BaseException("获取最高执行价信息错误");
        }
    }

    /**
     * 通过执行价和扣点系数调整溢价比
     *
     * @param pricePurchase    修改价格的支付信息
     * @param deductRate       扣点系数
     * @param actPurchasePrice 执行价
     * @return
     */
    public PricePurchase updateOverflowRate(PricePurchase pricePurchase, BigDecimal deductRate, BigDecimal actPurchasePrice) {
        if (Objects.isNull(pricePurchase)) {
            throw new BaseException("指定信息不存在");
        }

//        //判断id
//        if (Objects.isNull(id)) throw new BaseException("请选择要调价的信息");
//        //判断是否有应信息
//        PricePurchase pricePurchase = baseMapper.selectById(id);
        //判断是否有默认支付的标准价
        if (Objects.nonNull(pricePurchase.getExtPurchasePrice())) {
            //判断是否有传入扣点系数
            if (Objects.isNull(deductRate)) {
                PriceDeductRate priceDeductRate = priceDeductRateService.returnPriceDeductRate(pricePurchase.getLspId(), pricePurchase.getFleetId());
                if (Objects.nonNull(priceDeductRate) && Objects.nonNull(priceDeductRate.getRate())) {
                    deductRate = priceDeductRate.getRate().setScale(2, BigDecimal.ROUND_HALF_UP);
                } else {
                    deductRate = new BigDecimal(1).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
            }
            //判断是否有传入执行价
            if (Objects.nonNull(actPurchasePrice)) {
                pricePurchase.setActPurchasePrice(actPurchasePrice);
            }
            //暂估价=标准价*扣点系数
            BigDecimal extPurchasePrice = pricePurchase.getExtPurchasePrice().multiply(deductRate).setScale(2, BigDecimal.ROUND_HALF_UP);
            //执行价大于暂估价
            if (Objects.nonNull(pricePurchase.getActPurchasePrice()) &&
                    pricePurchase.getActPurchasePrice().compareTo(extPurchasePrice) == 1) {
                BigDecimal overflowRate = (pricePurchase.getActPurchasePrice().subtract(extPurchasePrice)).divide(extPurchasePrice, 2, BigDecimal.ROUND_HALF_UP);
                pricePurchase.setOverflowRate(overflowRate.toString());
            } else {
                pricePurchase.setOverflowRate("0");
            }
            baseMapper.updateAllColumnById(pricePurchase);
        }
        return pricePurchase;
    }

    /**
     * 根据收入价格标准价为空的数据重新获取价格
     */
    @Override
    public void getPricePurchase() {
        List<PricePurchase> pricePurchases = baseMapper.getPricePurchaseNoTenant();
        LOGGER.info("getPriceIncoming params {}", JSONObject.toJSONString(pricePurchases));
        for (PricePurchase pricePurchase : pricePurchases) {
            LOGGER.info("getPricePurchase params {}", JSONObject.toJSONString(pricePurchase));
            pricePurchase.setGmtModify(new Date());
            this.updateById(pricePurchase);
            String priceAndMiles = null;
            try {
                LOGGER.info("getPricePurchase url:{},param:{}", tmsUrl + queryPurchasePriceOtmUrl, pricePurchase.getShipOrderItemId().toString());
                priceAndMiles = HttpClientUtil.get(tmsUrl + queryPurchasePriceOtmUrl + "/"
                        + pricePurchase.getShipOrderItemId().toString(), null, socketTimeout);
                LOGGER.info("getPricePurchase url:{}, param:{}, result:{}", tmsUrl + queryPurchasePriceOtmUrl, pricePurchase.getShipOrderItemId().toString(), priceAndMiles);
            } catch (Exception e) {
                LOGGER.error("getPricePurchase url:{},p aram:{}, 超时异常:{}", tmsUrl + queryPurchasePriceOtmUrl, pricePurchase.getShipOrderItemId().toString(), e);
            }
            if (!StringUtils.isEmpty(priceAndMiles)) {
                JSONObject jsonObject = JSONObject.parseObject(priceAndMiles);
                Integer code = jsonObject.getInteger("code");
                JSONObject data = jsonObject.getJSONObject("data");
                if (code != null && code == 0 && data != null) {
                    //暂估价
                    pricePurchase.setExtPurchasePrice(data.getBigDecimal("price"));
                    //计价里程
                    pricePurchase.setMileage(data.getBigDecimal("miles"));
                    this.updateById(pricePurchase);
                } else {
                    LOGGER.error("获取价格里程失败 {}", jsonObject.getString("message"));
                }
            } else {
                LOGGER.error("连接OTM获取价格里程失败");
            }
        }
    }
}
